package hl.demosample.app.util

import android.content.ContentValues
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import com.bumptech.glide.Glide
import com.bumptech.glide.request.transition.Transition
import hl.demosample.R
import hl.demosample.app.weight.downloadpicture.*
import java.io.*

/*
* path: Download 
* Author:hl
* Create: 2021-08-04 10:53
* Changes (from 2021-08-04)
* Desc:保存图片到系统相册
*/
object DownloadPicture {
    /**保存图片到系统相册并刷新(方法一)**/
    fun downloadPicture(url: String, context: Context) {
        Glide.with(context).downloadOnly().load(url).into(object : FileTarget() {
            override fun onLoadStarted(placeholder: Drawable?) {
                super.onLoadStarted(placeholder)
                ToastUtils.showInCenter(context, context.getString(R.string.picshow_start_download))
                super.onLoadStarted(placeholder)
            }

            override fun onLoadFailed(errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                ToastUtils.showInCenter(context, context.getString(R.string.picshow_download_fail))
            }

            override fun onResourceReady(resource: File, transition: Transition<in File?>?) {
                super.onResourceReady(resource, transition)

                // 传入的保存文件夹名
                val downloadFolderName = "sample/Download"
                // 保存的图片名称
                var str1 = url.replace("sample.com.cn", "")
                str1 = str1.replace("http:", "")
                var fileName = str1.replace("/".toRegex(), "").replace(".jpg".toRegex(), "")
                val mimeType = ImageUtils.getImageTypeWithMime(resource.absolutePath)

                fileName = "$fileName.$mimeType"
                if (Build.VERSION.SDK_INT >= 29) { //Build.VERSION_CODES.Q
                    // 大于等于29版本的保存方法
                    val resolver = context.contentResolver
                    // 设置文件参数到ContentValues中
                    val values = ContentValues()
                    values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                    values.put(MediaStore.Images.Media.DESCRIPTION, fileName)
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/$mimeType")
                    // values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/" + downloadFolderName + "/");
                    values.put(
                        "relative_path",
                        Environment.DIRECTORY_PICTURES + "/" + downloadFolderName + "/"
                    )
                    val insertUri =
                        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                    var inputStream: BufferedInputStream? = null
                    var os: OutputStream? = null
                    try {
                        inputStream = BufferedInputStream(FileInputStream(resource.absolutePath))
                        if (insertUri != null) {
                            os = resolver.openOutputStream(insertUri)
                        }
                        if (os != null) {
                            val buffer = ByteArray(1024 * 4)
                            var len: Int
                            while (inputStream.read(buffer).also { len = it } != -1) {
                                os.write(buffer, 0, len)
                            }
                            os.flush()
                        }
                        val parentPath = Environment.DIRECTORY_PICTURES + "/" + downloadFolderName
                        val promptStr = String.format(
                            context.getString(R.string.picshow_save_phone),
                            parentPath
                        )
                        ToastUtils.showInCenter(context, promptStr)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        ToastUtils.showInCenter(
                            context,
                            context.getString(R.string.picshow_download_fail)
                        )
                    } finally {
                        try {
                            os?.close()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                        try {
                            inputStream?.close()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                } else {
                    // 低于29版本的保存方法
                    val path = Environment.getExternalStorageDirectory()
                        .toString() + "/" + downloadFolderName + "/"
                    FileUtils.createFileByDeleteOldFile(path + fileName)
                    val result = FileUtils.copyFile(resource, path, fileName)
                    if (result) {
                        val promptStr =
                            String.format(context.getString(R.string.picshow_save_phone), path)
                        ToastUtils.showInCenter(context, promptStr)
                        SingleMediaScanner(context, path + fileName) {
                            // scanning...
                        }
                    } else {
                        ToastUtils.showInCenter(
                            context,
                            context.getString(R.string.picshow_download_fail)
                        )
                    }
                }
            }
        })
    }
}